package cn.dapeng.thread;

import java.util.concurrent.locks.LockSupport;

/**
 * @BelongProject study
 * @BelongPackage cn.dapeng.thread
 * @Description 启动两个线程，一个干完，另一个再干
 *  * 线程间通信例子  使用LockSupport实现
 * @ClassName ThreadCommunicationT03
 * @Author xupenghong
 * @Date 2024/8/28 13:31
 * @Version 1.0.0
 */
public class ThreadCommunicationT03 {

    private int step = 0;
    private boolean runningState = true;
    private final static String STR = "1A2B3C4D";

    public synchronized void print(boolean state) {
        char[] chars = STR.toCharArray();

        if (runningState == state) {
            System.out.println(Thread.currentThread().getName() + ":" + chars[step++ % (chars.length)]);
            runningState = !runningState;
        }
    }

    static Thread t1 = null, t2 = null;

    public static void main(String[] args) {
        ThreadCommunicationT03 t = new ThreadCommunicationT03();

        t1 = new Thread(() -> {
            while (true) {
                t.print(true);
                LockSupport.unpark(t2);
                LockSupport.park();
            }

        }, "T1");

        t2 = new Thread(() -> {
            while (true) {
                t.print(false);
                LockSupport.unpark(t1);
                LockSupport.park();
            }
        }, "T2");

        t1.start();
        t2.start();

    }

}
